# 爬取彼岸网美女图片
import requests
from lxml import etree
import os

if __name__ == '__main__':
    url = 'https://pic.netbian.com/4kmeinv/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Mobile Safari/537.36',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
    }

    response = requests.get(url=url, headers=headers)
    page_text = response.text

    # 数据解析：src的属性值 alt属性
    etree_html = etree.HTML(page_text)
    li_list = etree_html.xpath('//div[@class="slist"]/ul/li')
    # print(li_list)

    # 创建一个文件夹
    if not os.path.exists('./picLibs'):
        os.mkdir('./picLibs')

    for li in li_list:
        img_src = 'https://pic.netbian.com' + li.xpath('./a/img/@src')[0]
        img_name = li.xpath('./a/img/@alt')[0] + '.jpg'
        # 解决中文乱码
        img_name = img_name.encode('ISO-8859-1').decode('GBK')
        # print(img_name + '=====' + img_src)

        # 图片数据
        img_data = requests.get(img_src, headers).content
        # print(img_data)
        img_path = 'picLibs/' + img_name
        with open(img_path, 'wb') as fp:
            fp.write(img_data)
            print(img_name, '下载成功')
